package com.example.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.exception.GuliException;
import com.example.eduservice.entity.EduSubject;
import com.example.eduservice.entity.ExcelSubjectData;
import com.example.eduservice.mapper.EduSubjectMapper;

/**
 * @Author:tjf
 * @Description:
 */
public class ExcelSubjectDataListener implements ReadListener<ExcelSubjectData> {
    private EduSubjectMapper subjectMapper;
    public ExcelSubjectDataListener() {
    }

    public ExcelSubjectDataListener(EduSubjectMapper subjectMapper) {
        this.subjectMapper = subjectMapper;
    }
    // 读取excel行数据
    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext analysisContext) {
        // 行数据为空
        if (data.getOneSubjectName() == null || data.getTwoSubjectName() == null){
            throw new GuliException(20001, "Excel数据不能为空");
        }
        // 判断一级分类是否已经存在
        EduSubject oneSubject = this.existSubject(data.getOneSubjectName(), "0");
        if (oneSubject == null){
            oneSubject = new EduSubject();
            oneSubject.setTitle(data.getOneSubjectName());
            oneSubject.setParentId("0");
            subjectMapper.insert(oneSubject);
        }
        // 判断二级分类是否已经存在
        EduSubject twoSubject = this.existSubject(data.getTwoSubjectName(), oneSubject.getId());
        if (twoSubject == null){
            twoSubject = new EduSubject();
            twoSubject.setTitle(data.getTwoSubjectName());
            twoSubject.setParentId(oneSubject.getId());
            subjectMapper.insert(twoSubject);
        }
    }

    /**
     * 判断分类是否存在的方法
     * @param oneSubjectName
     * @return
     */
    private EduSubject existSubject(String oneSubjectName, String pid) {
        // select * from xxx where title = xxx and parent_id=xxx
        LambdaQueryWrapper<EduSubject> queryWrapper = new LambdaQueryWrapper(EduSubject.class);
        queryWrapper.eq(EduSubject::getTitle, oneSubjectName);
        queryWrapper.eq(EduSubject::getParentId, pid);
        EduSubject eduSubject = subjectMapper.selectOne(queryWrapper);
        return eduSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
